import { listSimpleDictDataApi } from '@/api/common'

const dict = {
  state: () => ({
    dictMap: new Map(),
    isSetDict: false
  }),
  mutations: {},
  actions: {
    setDictMap({ state }) {
      return new Promise(async (resolve) => {
        const { data: list } = await listSimpleDictDataApi()
        // 设置数据
        const dictDataMap = new Map()
        list.forEach((dictData) => {
          // 获得 dictType 层级
          const enumValueObj = dictDataMap[dictData.dictType]
          if (!enumValueObj) {
            dictDataMap[dictData.dictType] = []
          }
          // 处理 dictValue 层级
          dictDataMap[dictData.dictType].push({
            value: dictData.value,
            label: dictData.label,
            colorType: dictData.colorType,
            cssClass: dictData.cssClass
          })
        })
        state.dictMap = dictDataMap
        state.isSetDict = true
        resolve(dictDataMap)
      })
    },
    async getDictByType({ state, commit, dispatch }, type) {
      const { isSetDict, dictMap } = state

      if (!isSetDict) {
        await dispatch('setDictMap')
        return state.dictMap[type]
      } else {
        return dictMap[type]
      }
    },
    async resetDict() {}
  }
}

export default dict
